"""
对pymysql的二次封装
定义一个MySQLClient的类
两个实例方法：
    select(sql)
    execute(sqls) 支持事务
"""
import pymysql
from lib.config import CONFIG
from lib.logger import Logger

class MySQLClient(object):
    logger = Logger()
    def __init__(self, host=None, port=None, database=None, user=None, password=None):
        self.db_info = {
            "host": CONFIG["database"]["host"] if host is None else host,
            "port": int(CONFIG["database"]["port"]) if port is None else port,
            "database": CONFIG["database"]["database"] if database is None else database,
            "user": CONFIG["database"]["user"] if user is None else user,
            "password": CONFIG["database"]["password"] if password is None else password
        }

    def select(self, sql):
        with pymysql.connect(**self.db_info) as connection:
            with connection.cursor() as cursor:
                self.logger.debug("执行SQL语句: "+sql)
                return cursor.execute(sql)

    def execute(self, sqls):
        with pymysql.connect(**self.db_info) as connection:
            with connection.cursor() as cursor:
                try:
                    for item in sqls:
                        self.logger.debug("执行SQL语句: " + item)
                        cursor.execute(item)
                except Exception as e:
                    self.logger.error("执行SQL语句错误: "+e)
                    connection.rollback()
                else:
                    self.logger.debug("所有的SQL语句执行成功!!!")
                    connection.commit()
